﻿import {Copy, Check} from "lucide-react";
import {useState} from "react";

function CopyButton({id}: { id: string }) {
    // 复制状态控制
    const [copied, setCopied] = useState(false);
    const onCopy = async () => {
        try {
            setCopied(true);
            // 获取代码块文本
            const text = document.getElementById(id)!.innerText;
            // 复制到剪贴板
            await navigator.clipboard.writeText(text);
            // 复制成功后重置状态
            setTimeout(() => {
                setCopied(false);
            }, 1000);
        } catch (error) {
            console.log(error);
        }
    };
    
    return (
        <button
            onClick={onCopy}
            className="inline-flex rounded-md p-2 absolute right-0"
        >
            <Copy
                size={16}
                className={`transition-all text-white ${copied ? "scale-0" : "scale-100"}`}
            />
            <Check
                size={16}
                className={`absolute transition-all text-success ${copied ? "scale-100" : "scale-0"}`}
            />
        </button>
    );
}

export default CopyButton;
